import sys
import os
import subprocess
import shutil
from pathlib import Path

class PdfSetup:
    def __init__(self):
        self.project_root = Path(__file__).parent
        self.requirements_file = self.project_root / "requirements.txt"
        self.venv_name = "pdf_venv"
        self.python_version = "3.11.13"
        # Python executable for creating venv (system python)
        self.system_python = sys.executable
        # Python executable inside venv (after creation)
        self.venv_python = self.project_root / self.venv_name / "Scripts" / "python.exe" if sys.platform == "win32" else self.project_root / self.venv_name / "bin" / "python"
        self.venv_path = self.project_root / self.venv_name
        if sys.platform == "win32":
            self.venv_activate = self.venv_path / "Scripts" / "activate"
            self.venv_deactivate = self.venv_path / "Scripts" / "deactivate"
        else:
            self.venv_activate = self.venv_path / "bin" / "activate"
            self.venv_deactivate = self.venv_path / "bin" / "deactivate"

    def print_info(self, message):
        """打印步骤信息"""
        print(f"\n{'='*50}")
        print(f"[步骤] {message}")
        print(f"{'='*50}")

    def setup(self):
        """设置环境"""
        self.print_info("开始设置环境")
        self.print_info("创建虚拟环境")
        self.create_venv()
        self.print_info("安装依赖")
        self.install_dependencies()
        self.print_info("环境设置完成")
        self.print_info("显示激活信息")
        self.print_activation_info()
        return True
        
    def print_activation_info(self):
        """显示激活信息"""
        self.print_info("显示虚拟环境路径")
        system = sys.platform
        
        print("\n" + "="*60)
        print("🎉 虚拟环境创建完成！")
        print("="*60)
        
        print(f"\n📁 虚拟环境位置: {os.path.abspath(self.venv_name)}")
        
        print("\n📋 使用方法:")
        
        if system == "win32":
            print("  方法1 - 直接运行:")
            print("    quick_run_venv.bat")
            print("\n  方法2 - 手动激活:")
            print("    quick_run_venv.bat")
            print("    然后运行: python main.py")
            print("\n  方法3 - 命令行激活:")
            print(f"    {self.venv_name}\\Scripts\\activate")
        else:
            print("  方法1 - 直接运行:")
            print("    ./quick_run_venv.sh")
            print("\n  方法2 - 手动激活:")
            print("    ./quick_run_venv.sh")
            print("    然后运行: python main.py")
            print("\n  方法3 - 命令行激活:")
            print(f"    source {self.venv_name}/bin/activate")
        
        print("\n💡 提示:")
        print("  - 激活虚拟环境后，命令行前缀会显示环境名称")
        print("  - 运行 'deactivate' 命令可以退出虚拟环境")
        print("  - 虚拟环境只需要创建一次，之后直接激活使用即可")
        return True

    def create_venv(self):
        """创建虚拟环境"""
        self.print_info("创建虚拟环境")
        if self.venv_path.exists():
            self.print_info("虚拟环境已存在")

            # 询问用户是否要重新构建虚拟环境
            user_input = input("虚拟环境已存在，是否要重新构建？(y/n): ").strip().lower()
            if user_input in ['y', 'yes']:
                self.print_info("删除现有虚拟环境")
                shutil.rmtree(self.venv_path)
                self.print_info("重新创建虚拟环境")
                subprocess.run([self.system_python, "-m", "venv", self.venv_name], cwd=self.project_root)
            else:
                self.print_info("使用现有虚拟环境")
                return True
            return
        self.print_info("创建虚拟环境")
        subprocess.run([self.system_python, "-m", "venv", self.venv_name], cwd=self.project_root)
        return True
    
    def install_dependencies(self):
        """安装依赖"""
        self.print_info("安装依赖")
        success = subprocess.run([str(self.venv_python), "-m", "pip", "install", "--upgrade", "pip"], cwd=self.project_root)
        if success.returncode != 0:
            self.print_info("安装pip失败")
            return False
        success = subprocess.run([str(self.venv_python), "-m", "pip", "install", "-r", str(self.requirements_file), "-i", "https://pypi.tuna.tsinghua.edu.cn/simple", "--trusted-host", "pypi.tuna.tsinghua.edu.cn"], cwd=self.project_root)
        if success.returncode != 0:
            self.print_info("安装依赖失败")
            return False
        self.print_info("安装依赖完成")
        return True
    

def main():
    """主函数"""
    setup = PdfSetup()
    
    try:
        success = setup.setup()
        if success:
            print("环境设置成功")
            sys.exit(0)
        else:
            print("环境设置失败")
            sys.exit(1)
    except KeyboardInterrupt:
        print("\n用户中断")
        sys.exit(1)
    except Exception as e:
        print(f"发生错误: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()